import Food from './Food';
import ScorePanel from './ScorePanel';
import Snake from './Snake';
class GameControl {
  snake: Snake;
  food: Food;
  scorePanel: ScorePanel;
  arrEnum = new Array(
    'ArrowUp',
    'Up',
    'ArrowDown',
    'Down',
    'ArrowLeft',
    'Left',
    'ArrowRight',
    'Right'
  );

  // 按键方向
  direction: string = 'Right';
  // 游戏时候结束
  isLive: boolean = true;

  constructor() {
    this.snake = new Snake();
    this.food = new Food();
    this.scorePanel = new ScorePanel(10, 10);
    this.init();
  }

  init() {
    document.addEventListener('keydown', this.keydownHandler.bind(this));
    this.run();
  }

  keydownHandler(event: KeyboardEvent) {
    if (this.arrEnum.indexOf(event.key) < 0) {
      return;
    }

    this.direction = event.key;
  }

  // 蛇移动
  run() {
    let x = this.snake.x;
    let y = this.snake.y;

    switch (this.direction) {
      case 'ArrowUp':
      case 'Up':
        y -= 10;
        break;
      case 'ArrowDown':
      case 'Down':
        y += 10;
        break;
      case 'ArrowLeft':
      case 'Left':
        x -= 10;
        break;
      case 'ArrowRight':
      case 'Right':
        x += 10;
        break;
    }

    // 检查蛇是否吃到了实物
    this.checkEatHandler(x, y);

    // 修改蛇的x和y
    try {
      this.snake.x = x;
      this.snake.y = y;
    } catch (e: any) {
      alert(e.message);
      this.isLive = false;
    }

    this.isLive &&
      setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30);
  }

  checkEatHandler(x: number, y: number) {
    if (x === this.food.x && y === this.food.y) {
      this.food.change();
      this.scorePanel.addScore();
      this.snake.addBody();
    }
  }
}

export default GameControl;
